<script setup>
import {computed, onMounted, ref} from 'vue'
import {deleteUserByid, getAllUser,getUserById,updateUser} from '@/api/admin.js'
import {ElDialog, ElMessage, ElMessageBox} from 'element-plus'
import {Message, OfficeBuilding, Phone, Reading, School, UserFilled} from '@element-plus/icons-vue'
const users = ref([])
const currentPage = ref(1)
const pageSize = ref(9)
const total = ref(0)
const loading = ref(false)

const selectedCollege = ref('')
const selectedClass = ref('')


// 搜索条件
const searchQuery = ref('')

// 获取用户数据
const fetchUserList = async () => {
  loading.value = true
  try {
    const resp = await getAllUser(currentPage.value, pageSize.value)
    users.value = resp.data.records
    total.value = resp.data.total
  } catch (error) {
    console.error('Error fetching data:', error)
  } finally {
    loading.value = false
  }
}

// 页面加载时获取数据
onMounted(fetchUserList)

// 提取唯一的学院和班级名称
const uniqueColleges = computed(() => {
  const colleges = users.value.map(user => user.collegename)
  return [...new Set(colleges)] // 使用 Set 去重
})

const uniqueClasses = computed(() => {
  const classes = users.value.map(user => user.classname)
  return [...new Set(classes)] // 使用 Set 去重
})

// 过滤用户数据
const filteredUsers = computed(() => {
  return users.value.filter(user => {
    const matchCollege = selectedCollege.value ? user.collegename === selectedCollege.value : true
    const matchClass = selectedClass.value ? user.classname === selectedClass.value : true
    return matchCollege && matchClass
  })
})

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchUserList()
}

// 重置搜索
const resetSearch = () => {
  selectedCollege.value = ''
  selectedClass.value = ''
  fetchUserList()
}

// 处理分页变化
const handlePageChange = (page) => {
  currentPage.value = page
  fetchUserList()
}


//删除
const deleteUser = async (userId) => {
  try {
    await ElMessageBox.confirm('此操作将永久删除该用户, 是否继续?', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await deleteUserByid(userId)
    fetchUserList()
    ElMessage.success('删除成功')
  } catch (error) {
    if (error === 'cancel') {
      ElMessage.info('删除已取消')
    } else {
      ElMessage.error('删除失败，请重试')
    }
  }
}


const currentUser = ref([])
const dialogVisible = ref(false);

const colleges = ref([])    //获取学院信息
const classes = ref([])   //获取班级信息
//弹窗
const editUser = async (userId) => {
  try {
    const resp = await getUserById(userId);
    // 将选中的用户数据填充到 currentUser 中
    currentUser.value = resp.data.user;  
    //填充学院信息
    colleges.value = resp.data.colleges
    //填充班级信息
    classes.value = resp.data.classes
    dialogVisible.value = true;
  } catch (error) {
    ElMessage.error('获取用户信息失败');
  }
};

// 提交编辑数据
const handleEditSubmit = async () => {
  try {
    await updateUser(currentUser.value);  // 提交更新后的数据到服务器
    ElMessage.success('更新成功');
    dialogVisible.value = false;
    fetchUserList();  // 更新后刷新用户列表
  } catch (error) {
    ElMessage.error('更新失败');
  }
};


</script>

<template>
  <div>
    <!-- 搜索表单 -->
    <el-form :inline="true" @submit.native.prevent="handleSearch">
      <el-form-item>
        <el-select v-model="selectedCollege" placeholder="选择学院" style="width: 200px;">
          <el-option
            v-for="college in uniqueColleges"
            :key="college"
            :label="college"
            :value="college">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select v-model="selectedClass" placeholder="选择班级" style="width: 200px;">
          <el-option
            v-for="className in uniqueClasses"
            :key="className"
            :label="className"
            :value="className">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button type="primary" @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 用户列表 -->
    <el-table :data="filteredUsers" style="width: 100%" v-loading="loading">
      <!-- 序号列 -->
      <el-table-column 
        label="序号" 
        width="80" 
        type="index"  
        :index="(index) => (currentPage - 1) * pageSize + index + 1">
      </el-table-column>

      <!-- 其他列 -->
      <el-table-column prop="userId" label="ID" width="80" v-if="false"></el-table-column>
      <el-table-column prop="username" label="姓名" width="100"></el-table-column>
      <el-table-column 
        prop="status" 
        label="身份" 
        width="100"
        :formatter="(row) => {
          switch (row.status) {
            case 1:
              return '管理员';
            case 2:
              return '裁判';
            default:
              return '学生';
          }
        }">
      </el-table-column>
      <el-table-column prop="gender" label="性别" width="80" :formatter="(row) => (row.gender === '1' ? '男' : '女')"></el-table-column>
      <el-table-column prop="collegename" label="学院" width="100"></el-table-column>
      <el-table-column prop="classname" label="班级" width="100"></el-table-column>
      <el-table-column prop="studentId" label="学号" width="100"></el-table-column>
      <el-table-column prop="phone" label="联系电话" width="150" :formatter="(row) => row.phone || '未填写'"></el-table-column>
      <el-table-column prop="email" label="邮箱" width="200"></el-table-column>

      <!-- 操作列 -->
      <el-table-column label="操作" width="180">
        <template v-slot="scope">
          <el-button size="small" type="primary" @click="editUser(scope.row.userId)">编辑</el-button>
          <el-button @click="deleteUser(scope.row.userId)" type="danger" size="small" style="margin-left: 10px;">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      @current-change="handlePageChange"
      :current-page="currentPage"
      :page-size="pageSize"
      :total="total"
      layout="total, prev, pager, next, jumper"
      style="margin-top: 20px">
    </el-pagination>


    <!--    编辑信息弹窗-->
    <el-dialog v-model="dialogVisible" title="编辑信息" width="500">
  <template #default>
    <el-form :model="currentUser" style="max-width: 480px; height: 400px">
      <!-- 姓名 -->
      <el-form-item label="姓名" prop="username">
        <el-input v-model="currentUser.username" :suffix-icon="UserFilled"></el-input>
      </el-form-item>

      <!-- 身份选择 -->
      <el-form-item label="身份" prop="status">
        <el-select v-model="currentUser.status" placeholder="请选择身份" :suffix-icon="User">
          <el-option label="学生" :value="0"></el-option>
          <el-option label="管理员" :value="1"></el-option>
          <el-option label="裁判" :value="2"></el-option>
        </el-select>
      </el-form-item>

      <!-- 性别 (单选框) -->
      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="currentUser.gender">
          <el-radio label="1">男</el-radio>
          <el-radio label="0">女</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 学院 (根据 collegeId 选择学院) -->
      <el-form-item label="学院" prop="collegeId">
        <el-select v-model="currentUser.collegeId" placeholder="请选择学院" :suffix-icon="OfficeBuilding">
          <el-option
            v-for="college in colleges"
            :key="college.collegeId"
            :label="college.name"
            :value="college.collegeId">
          </el-option>
        </el-select>
      </el-form-item>

      <!-- 班级 (根据 classId 选择班级) -->
      <el-form-item label="班级" prop="classId">
        <el-select v-model="currentUser.classId" placeholder="请选择班级" :suffix-icon="School">
          <el-option
            v-for="classItem in classes"
            :key="classItem.classId"
            :label="classItem.name"
            :value="classItem.classId">
          </el-option>
        </el-select>
      </el-form-item>

      <!-- 学号 -->
      <el-form-item label="学号" prop="studentId">
        <el-input v-model="currentUser.studentId" :suffix-icon="Reading"></el-input>
      </el-form-item>

      <!-- 邮箱 -->
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="currentUser.email" :suffix-icon="Message" placeholder="**@**.com"></el-input>
      </el-form-item>

      <!-- 联系电话 -->
      <el-form-item label="联系电话" prop="phone">
        <el-input v-model="currentUser.phone" :suffix-icon="Phone"></el-input>
      </el-form-item>
    </el-form>
  </template>

  <!-- 弹窗底部操作按钮 -->
  <template #footer>
    <div class="dialog-footer">
      <el-button @click="dialogVisible = false">关闭</el-button>
      <el-button type="primary" @click="handleEditSubmit">确定</el-button>
    </div>
  </template>
</el-dialog>



  </div>
</template>

<style scoped>
.el-table {
  margin-top: 20px;
}

.el-form {
  margin-bottom: 20px;
}
</style>
